package spe.ui.editor;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPartViewer;
import org.eclipse.gef.ui.parts.SelectionSynchronizer;
import org.eclipse.gef.ui.parts.TreeViewer;

import spe.model.notation.SPEMDiagram;
import spe.model.spem.SPEMElement;
import spe.ui.editor.part.AbstractElementNodeEditPart;
import spe.ui.editor.part.OutlineEditPart;

public class SPESelectionSynchronizer extends SelectionSynchronizer
{
	protected EditPart convert(EditPartViewer viewer, EditPart part) 
	{
		if (viewer instanceof MyScrollingGraphicalViewer && part instanceof OutlineEditPart) 
		{
			part = getSelectablePartInGraphicalViewer(part);
			SPEMDiagram diagram = ((SPEMEditorInput)(((MyScrollingGraphicalViewer)viewer).getEditor().getEditorInput())).getModel();
			SPEMElement element = diagram.getElements().get(0);
			if (element != null) 
			{
				return (EditPart)viewer.getEditPartRegistry().get(element);
			}
		}
		if (viewer instanceof TreeViewer && part instanceof AbstractElementNodeEditPart) 
		{
			Object semanticElement = ((AbstractElementNodeEditPart)part).getModel();
			if (semanticElement != null) 
			{
				EditPart result = (EditPart)viewer.getEditPartRegistry().get(semanticElement);
				while (result != null && result.getParent() != null && result.getParent().getModel() == semanticElement) {
					result = result.getParent();
				}
				return result; 
			}
		}
		return null;
	}
	
	private EditPart getSelectablePartInGraphicalViewer(EditPart part) {
		while (!isSelectablePartInGraphicalViewer(part)) {
			if (part.getParent() == null) break;
			part = part.getParent();
		}
		return part;
	}
	
	protected boolean isSelectablePartInGraphicalViewer(EditPart part) {
		return true;
	}

}
